package org.plr.ecommerce.controler;

import org.hibernate.SessionFactory;
import org.plr.ecommerce.model.Entity;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public abstract class EntityControler<ENTITY extends Entity> implements ApplicationContextAware {

    private ApplicationContext applicationContext = null;

    private SessionFactory sessionFactory = null;

    private ENTITY entity = null;

    public EntityControler(ENTITY entity) {
        setEntity(entity);
    }

    public ApplicationContext getApplicationContext() {
        return this.applicationContext;
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public SessionFactory getSessionFactory() {
        return this.sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public ENTITY getEntity() {
        return this.entity;
    }

    public void setEntity(ENTITY entity) {
        this.entity = entity;
        if (this.entity instanceof EntityControler) {
            EntityControler<ENTITY> entityControler = (EntityControler<ENTITY>) this.entity;
            this.entity = entityControler.getEntity();
        }
    }

    public void create() {
        this.getSessionFactory().getCurrentSession().persist(this.getEntity());
    }

    public void read() {
        this.getSessionFactory().getCurrentSession().refresh(this.getEntity());
    }

    public void update() {
        this.getSessionFactory().getCurrentSession().merge(this.getEntity());
    }

    public void delete() {
        this.getSessionFactory().getCurrentSession().delete(this.getEntity());
    }
}
